package com.lzy.crm.wechat.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonObject;
import com.lzy.crm.base.date.DateUtil;
import com.lzy.crm.base.util.JsonUtil;
import com.lzy.crm.base.util.Md5Util;
import com.lzy.crm.base.util.StringUtil;
import com.lzy.crm.domain.PpUser;
import com.lzy.crm.domain.User;
import com.lzy.crm.service.CardFlowService;
import com.lzy.crm.service.ParamService;
import com.lzy.crm.service.PpUserService;
import com.lzy.crm.service.UserService;
import com.lzy.crm.util.UserConstants;
import com.lzy.crm.vo.PlayerInfo;
import com.lzy.crm.vo.SystemStatusInfo;
import com.lzy.crm.wechat.consts.WechatPayProperties;
import com.lzy.crm.wechat.util.ImgUtil;
import com.lzy.crm.wechat.util.WeixinUtil;
import com.lzy.crm.wechat.vo.Message;

@Controller
@RequestMapping("/wechat")
public class WechatController {

	Logger logger = Logger.getLogger(WechatController.class);
	
	@Resource
	private UserService userService;

	
	@Resource
	private PpUserService pUserService;
	
	
	@Resource
	private CardFlowService cardFlowService;
	
	@Resource
	private ParamService paramService;
	
	
	private String wechatAccounts ="郴州互娱";
	
	//微信登陆代理商平台
	@RequestMapping("/login")
	public String login(HttpServletRequest request, ModelMap model) {
		
		PpUser user =(PpUser)request.getSession().getAttribute("userSession");
		// 订单信息
		if(user==null||StringUtil.isEmpty(user.getOpenid())
				||StringUtil.isEmpty(user.getUnionid())
				){
			model.put("appid", WechatPayProperties.getAppId());
			model.put("redirectUri", WechatPayProperties.getRedirectUri()+"?page=wechat/login.html");
			return "wechat/index2"; 
		}
		/*if(user == null){
			// 跳转到成为代理商登陆界面
			model.put("message", "尊敬的用户你好，请先下载app,才能登陆代理后台,谢谢支持 ~~ ");
			return "../../login"; 
		}*/
		/*if(user.getFreeze().compareTo(1)!=-1){
			// 跳转到成为代理商登陆界面
			model.put("message", "账号已封禁，请联系管理员~");
			return "../../login"; 
		}*/
		/*if(!(StringUtil.equals(user.getRid()+"", UserConstants.USER_TYPE_AGENT)||StringUtil.equals(user.getRid()+"", UserConstants.USER_TYPE_MANAGE))){
			// 跳转到成为代理商登陆界面
			model.put("message", "代理后台，现在只限代理开放~");
			return "../../login"; 
		}*/
		return "mobile/index"; // 手机端
	}
	
	/**
	 * 微信首页游戏列表
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/index2")
	public String index(HttpServletRequest request, ModelMap model) {
		String gameId =request.getParameter("gameId");
		String retUrl =  WechatPayProperties.getRedirectUri();
		if(StringUtil.isNotEmpty(gameId)){
			retUrl += "?gameId="+gameId;
		}
		model.put("appid", WechatPayProperties.getAppId());
		model.put("redirectUri",retUrl );
		return "wechat/index2";
	}

	/**
	 * 获取授权接口
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/retindex")
	public String weixinLogin(HttpServletRequest request,
			HttpServletResponse response,ModelMap model)  {
		try {
			String page = request.getParameter("page");
			Map<String, String[]> params = request.getParameterMap();// 针对get获取get参数
			String[] codes = params.get("code");// 拿到的code的值
			boolean isweixin = WeixinUtil.isWeiXin(request);
			// 非微信请求跳到游戏列表页面
			if (!isweixin) {
				return "wechat/game_list";
			}
			if(codes==null){
				System.out.println("返回出去");
				return null;
			}
			String code = codes[0];// code
			// 这一步就是拼写微信api请求地址并 通过微信的appid 和 微信公众号的AppSecret 以及我们获取到的针对用户授权回调的code
			// 拿到 这个用户的 openid和access_token
			String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code"
					.replace("APPID", WechatPayProperties.getAppId())
					.replace("APPSECRET", WechatPayProperties.getAppSecret())
					.replace("CODE", code);
			JsonObject getCodeResultJson = WeixinUtil.HttpRequest(requestUrl,
					"GET", null);
			if (getCodeResultJson == null
					|| getCodeResultJson.get("errcode") != null
					|| getCodeResultJson.get("openid") == null) {
				// throw "";//这里需要抛异常 如果返回值没有 或者 出现错误返回errcode 或者 没有拿到openid
			}
			// 刷新 未拿到openID 情况
			if(getCodeResultJson.get("unionid")==null){
				return "wechat/game_list";
			}
			String openid = getCodeResultJson.get("openid").getAsString();// 拿到openid
			String unionid = getCodeResultJson.get("unionid").getAsString();// 拿到unionid
			String access_token = getCodeResultJson.get("access_token").getAsString();
			//System.out.println("第一把参数" + JsonUtil.toJson(getCodeResultJson));
			PpUser user = pUserService.getPpUserByUnionId(unionid);
			
			
			if (user != null && StringUtil.isNotEmpty(user.getOpenid()) ) {
				request.getSession().setAttribute("userSession", user);
			}else{
				// 补全信息 或生成信息
				String unioinidrequestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"
						.replace("OPENID", openid).replace("ACCESS_TOKEN",
								access_token);
				JsonObject userinfoJson = WeixinUtil.HttpRequest(
						unioinidrequestUrl, "GET", null);
				
				String nickname =userinfoJson.get("nickname").getAsString();
				String headimgurl= userinfoJson.get("headimgurl").getAsString();
				String sex = userinfoJson.get("sex").getAsString();
				String province = userinfoJson.get("province").getAsString();
				String city = userinfoJson.get("city").getAsString();
				
				user=new PpUser();
				user.setUphone(null);       //      `uphone` varchar(11) NOT NULL DEFAULT ' ' COMMENT '手机号码',
				user.setWechat(null);     	//          `wechat` varchar(60) NOT NULL DEFAULT ' ' COMMENT 'wechat',
				user.setRealname(null); 	//  `realname` varchar(30) NOT NULL DEFAULT ' ' COMMENT '真实姓名',
				user.setIdnum(null);              //   `idnum` varchar(18) NOT NULL DEFAULT '暂缺' COMMENT '身份证号',
				user.setPwd("e10adc3949ba59abbe56e057f20f883e"); // `pwd` varchar(50) NOT NULL DEFAULT '暂缺' COMMENT '密码',
				user.setHeadImgUrl(headimgurl);    // `head_img_url` varchar(200) NOT NULL DEFAULT '暂缺' COMMENT '头像url',
				user.setAddress(province+city);             // `address` varchar(200) NOT NULL DEFAULT '暂缺' COMMENT '详细地址',
				user.setRid(5);                    // `rid` int(10) unsigned NOT NULL DEFAULT '5' COMMENT '角色id',
				user.setFrontUid(null);            // `front_uid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '上级用户id',
				user.setChiefUid(null);            // `chief_uid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '总代用户id',
				user.setNickname(nickname);        // `nickname` varchar(30) NOT NULL DEFAULT '暂缺' COMMENT '昵称',
				user.setRoomcard(10);              // `roomcard` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '房卡数',
				user.setBubble(0);                      // `bubble` int(11) NOT NULL DEFAULT '0' COMMENT '金数',
				user.setRechargeUid(null);              // `recharge_uid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '分数充值人id',
				user.setFreeze(2);                      // `freeze` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '1-冻结,2-解冻',
				user.setCreateTime(new Date());     // `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
				user.setUpperLimit(null);              // `upper_limit` int(11) NOT NULL DEFAULT '0' COMMENT '分数上限',
				user.setLowerLimit(null);             // `lower_limit` int(11) NOT NULL DEFAULT '0' COMMENT '分数下限',
				user.setSex(Integer.parseInt(sex));    // `sex` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '1:男，2：女',
				user.setAccessTime(new Date());          // `access_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近访问时间',
				user.setUnionid(unionid);                // `unionid` varchar(50) DEFAULT '' COMMENT '微信unionid',
				user.setOpenid(openid);                   // `openid` varchar(50) DEFAULT '' COMMENT '微信openid',
				user.setToken(access_token);           // `token` varchar(150) DEFAULT '' COMMENT 'token',
				user.setRefreshToken(null);            // `refresh_token` varchar(150) DEFAULT '' COMMENT '刷新token',
				user.setMoney(0);                                  // `money` int(11) NOT NULL DEFAULT '0' COMMENT 'RMB',
				user.setUstate(0);                                   // `ustate` int(11) NOT NULL DEFAULT '0' COMMENT '状态',
				user.setFlag(0);                      // `flag` int(11) NOT NULL DEFAULT '0' COMMENT '首冲等活动标签',
				user.setBackgold(0.0);                               // `backgold` decimal(10,0) unsigned NOT NULL DEFAULT '0' COMMENT '返现',
				user.setBackcard(0);                                   // `backcard` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '返卡次数',
				user.setRoomId(0);                                   // `room_id` int(10) unsigned DEFAULT '0',
				user.setCode(0);                                   // `code` int(10) DEFAULT '0' COMMENT '推广码',
				user.setUserLevel(9);                                 // `user_level` int(11) DEFAULT '9' COMMENT '分润等级',
				Integer newUid = pUserService.insertSelective(user);
			}
			model.put("msg", "登录成功");
			if(StringUtil.isNotEmpty(page)){
				return "redirect:/"+page; 
			}
			
			
		} catch (Exception e) {
			logger.error("用户授权登陆错误", e);
		}
		return "wechat/game_list";
	}
	
	
	/**
		// 我们需要获取当前公众号通用的access_token 和用户的access_token是不一样的
		// 这里我为了让大家可以方便就没有写太复杂 因为微信他那边获取微信公众号的通用access_token每天只能取2000次
		// 每次token有效期是7200S 所以在自己动手写最好放在缓存中 我的项目放在redis中
		String access_token = WeixinUtil.getAccessToken(WechatPayProperties.getAppId(),WechatPayProperties.getAppSecret()).getToken();
		
		// 这里是获取用户在我们公众里面的信息 如果没有关注公众号那么就没有办法获取详细信息 参数需要 微信公众号通用token 和 用户openid
		String requestUrl2 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"
				.replace("ACCESS_TOKEN", access_token).replace("OPENID",openid);
		JsonObject userJson = WeixinUtil.HttpRequest(requestUrl2, "GET", null);
		if (userJson == null || userJson.get("errcode") != null) {
			// 抛异常
		}
		System.out.println(JsonUtil.toJson(userJson));
		Integer subscribe = userJson.get("subscribe").getAsInt();// 是否有关注我们公众号
		
		
		
		if (subscribe == 0) {// 没有关注我们公众号
			response.sendRedirect("https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzIyNTc1MDQ2Mw==&scene=110#wechat_redirect");
			// 跳到我们公众号关注页面 url地址需要你么你自己去截取
		} else {// 关注了
				// 如果关注了 user中就会有详细的信息 我们既可以把这些信息存在我们的数据库中 然后跳转到我们前台页面
			System.out.println("关注过");
			

		} **/

	
	@RequestMapping("/index")
	public String index2(HttpServletRequest request, ModelMap model) {
		return "wechat/game_list";
	}

	@RequestMapping(path="/token",method=RequestMethod.GET,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getToken(HttpServletRequest request, ModelMap model) {
		Map<String, String[]> params = request.getParameterMap();// 针对get获取get参数
		
		System.out.println("get 请求关注公众号参数：" + JsonUtil.toJson(params));
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// SHA1加密
		String pwd = "";
		if (signature != null && timestamp != null && nonce != null) {
			String[] strSet = new String[] { WeixinUtil.TOKEN, timestamp, nonce };
			java.util.Arrays.sort(strSet);
			String key = "";
			for (String string : strSet) {
				key = key + string;
			}
			pwd = WeixinUtil.sha1(key);
		}

		// 确认请求来至微信
		if (pwd.equals(signature)) {

			return echostr;
		} else {
			return "error";
		}

	}
	
	@ResponseBody
	@RequestMapping(path="/token",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	public String postToken(HttpServletRequest request, ModelMap model) {
		try {
			String backContext ="尊敬的用户，您好！欢迎关注"+wechatAccounts+"微信服务号。";
			// 仅处理微信服务端发的请求
			if (checkWeixinReques(request)) {
				
			}
				Map<String, String> requestMap = WeixinUtil.parseXml(request);
				System.out.println(JsonUtil.toJson(requestMap));
				final Message message = WeixinUtil.mapToMessage(requestMap);
				// 保存和取消微信相关数据
				if(message.getEvent().equals("subscribe")){
					// 创建用户信息
					createUserInfo( request, message);
					System.out.println("已关注");
					backContext+=" 点击\"下载游戏\"即可进行下载，感谢您的支持！ ";
				}else if(message.getEvent().equals("unsubscribe")){
					System.out.println("未关注");
				}else if(message.getEvent().equals("CLICK")){
					// 推送二维码消息 
					if(StringUtil.equals(message.getEventKey(), "img") ){
						return showQrCode( request, message);
					}else if(StringUtil.equals(message.getEventKey(), "kefu") ){
						return kefu(request, message);
					}
				}else if(message.getEvent().equals("VIEW")){
					String openid =message.getFromUserName();
					if(request.getSession().getAttribute("userSession")==null){
						PpUser user = pUserService.getPpUserByopenid(openid); 
						if(user!=null){
							// 以创建游戏
							request.getSession().setAttribute("userSession", user);
						}
					}
				}
				// 拼装回复消息
				String  back="<xml><ToUserName><![CDATA["+message.getFromUserName()+"]]></ToUserName>"
						+"<FromUserName><![CDATA["+message.getToUserName()+"]]></FromUserName>"
						+"<CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType>"
						+"<Content><![CDATA["+backContext+"]]></Content></xml>";
				return back;
			/*}else{ 
				logger.info("非微信请求");
				return "error";
			}*/
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("post token 关注错误 ",e);
			return "error";
		}
	}
	
	
	
	
	/**
	 * 创建玩家信息
	 */
	public String createUserInfo(HttpServletRequest request,Message message)throws Exception{
		String  back =null;
		//"EventKey":"qrscene_100917"
		String openid =message.getFromUserName();
		String access_token = WeixinUtil.getAccessToken(WechatPayProperties.getAppId(),WechatPayProperties.getAppSecret()).getToken();
		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
		JsonObject userinfoJson = WeixinUtil.HttpRequest(
				url, "GET", null);
		User user = userService.getUserByUnionid(userinfoJson.get("unionid").getAsString());
		Integer roomCardMenInvited = UserConstants.ROOM_CARD_INVITED;
		if(user!=null){
			if(user.getParentId()==null||user.getParentId()==0){
				String pgameId = message.getEventKey().replace("qrscene_", "");
				// 是否已创建游戏
				PlayerInfo playerInfo = userService.getPlayerInfo(null, userinfoJson.get("unionid").getAsString());
				User prarentUser = null;
				Integer parentId = 0;
				Integer upParentId =0;
				// 游戏已填写邀请
				if(playerInfo!=null&& !StringUtil.equals(playerInfo.getSpreaderId(), "0")){
					//您邀请的用户 以成功绑定 公众号
					prarentUser = userService.getUserInfoByGameid(playerInfo.getSpreaderId());
					// 绑定关系
					if(prarentUser!=null){
						parentId =prarentUser.getId();
						upParentId = prarentUser.getParentId();
						prarentUser.setParentNub((prarentUser.getParentNub()==null?0:prarentUser.getParentNub())+1);  // 增加第一邀请人 数
						userService.updateByPrimaryKeySelective(prarentUser);
						if(upParentId!=0&&upParentId!=null){
							User upParentUser = userService.getById(upParentId);
							if(upParentUser!=null){
								upParentUser.setUpParentNub(upParentUser.getUpParentNub()==null?0:upParentUser.getUpParentNub()+1);
								userService.updateByPrimaryKeySelective(upParentUser);
							}
						}
					}
					//retParentMes( access_token, userinfoJson.get("nickname").getAsString(),prarentUser,roomCardMenInvited);
				}else if(!StringUtil.equals(pgameId, "0")&&pgameId.length()>0){
					//带参数二维码
					prarentUser = userService.getUserInfoByAgentId(pgameId);
					if(prarentUser==null){
						prarentUser=userService.getUserInfoByGameid(pgameId);
					}
					// 写入父类关系
					if(prarentUser!=null){
						parentId =prarentUser.getId();
						upParentId = prarentUser.getParentId();
						prarentUser.setParentNub((prarentUser.getParentNub()==null?0:prarentUser.getParentNub())+1);  // 增加第一邀请人 数
						userService.updateByPrimaryKeySelective(prarentUser);
						PlayerInfo parentPlayerInfo = userService.getPlayerInfo(prarentUser.getGameUserId(), null);
						
						// 第一次创建用户 给邀请人赠送房卡
						// 非推广大师都是
						if(prarentUser.getUserLevel()!=null&&!StringUtil.equals(prarentUser.getUserLevel(), UserConstants.USER_LEVEL_TGDS)
								){
							roomCardMenInvited = UserConstants.ROOM_CARD_INVITED_AGENT;				
						}
						//userService.addPlayerCard(parentPlayerInfo.getUserId(), roomCardMenInvited);
						userService.invitedAddPlayerCard(prarentUser, parentPlayerInfo, roomCardMenInvited,userinfoJson.get("nickname").getAsString());
						// 推送邀请信息
						retParentMes( access_token, userinfoJson.get("nickname").getAsString(),prarentUser,roomCardMenInvited);
						// 写入上 上级邀请ID
						if(upParentId!=0&&upParentId!=null){
							User upParentUser = userService.getById(upParentId);
							if(upParentUser!=null){
								upParentUser.setUpParentNub(upParentUser.getUpParentNub()==null?0:upParentUser.getUpParentNub()+1);
								userService.updateByPrimaryKeySelective(upParentUser);
							}
						}
					}
				}
				// 绑定邀请人
				user.setParentId(parentId);
				user.setUpParentId(upParentId);
			}
			user.setOpenid(openid);
			userService.updateByPrimaryKeySelective(user);
			// 以创建信息
			request.getSession().setAttribute("userSession", user);
		}else{
			// 未创建信息
			/** 获取房卡赠送数 **/
			
			List<SystemStatusInfo> systemStatusInfoList= paramService.getSystemStatusInfoByStatusName("RoomCardMenInvited");
			if(systemStatusInfoList!=null&&systemStatusInfoList.size()>0){
				roomCardMenInvited =systemStatusInfoList.get(0).getStatusValue();
			}
			// 是否已创建游戏
			PlayerInfo playerInfo = userService.getPlayerInfo(null, userinfoJson.get("unionid").getAsString());
			User prarentUser = null;
			Integer parentId = 0;
			Integer upParentId =0;
			Integer totalCard = 0 ;
			String pgameId = message.getEventKey().replace("qrscene_", "");
			// 游戏已填写邀请
			if(playerInfo!=null&& !StringUtil.equals(playerInfo.getSpreaderId(), "0")){
				//您邀请的用户 以成功绑定 公众号
				prarentUser = userService.getUserInfoByGameid(playerInfo.getSpreaderId());
				// 绑定关系
				if(prarentUser!=null){
					parentId =prarentUser.getId();
					upParentId = prarentUser.getParentId();
					prarentUser.setParentNub((prarentUser.getParentNub()==null?0:prarentUser.getParentNub())+1);  // 增加第一邀请人 数
					userService.updateByPrimaryKeySelective(prarentUser);
					if(upParentId!=0&&upParentId!=null){
						User upParentUser = userService.getById(upParentId);
						if(upParentUser!=null){
							upParentUser.setUpParentNub(upParentUser.getUpParentNub()==null?0:upParentUser.getUpParentNub()+1);
							userService.updateByPrimaryKeySelective(upParentUser);
						}
					}
				}
				//retParentMes( access_token, userinfoJson.get("nickname").getAsString(),prarentUser,roomCardMenInvited);
			}else if(!StringUtil.equals(pgameId, "0")&&pgameId.length()>0){
				//带参数二维码
				prarentUser = userService.getUserInfoByAgentId(pgameId);
				if(prarentUser==null){
					prarentUser=userService.getUserInfoByGameid(pgameId);
				}
				// 写入父类关系
				if(prarentUser!=null){
					parentId =prarentUser.getId();
					upParentId = prarentUser.getParentId();
					prarentUser.setParentNub((prarentUser.getParentNub()==null?0:prarentUser.getParentNub())+1);  // 增加第一邀请人 数
					userService.updateByPrimaryKeySelective(prarentUser);
					PlayerInfo parentPlayerInfo = userService.getPlayerInfo(prarentUser.getGameUserId(), null);
					
					// 非推广大师都是
					if(prarentUser.getUserLevel()!=null&&!StringUtil.equals(prarentUser.getUserLevel(), UserConstants.USER_LEVEL_TGDS)
							){
						roomCardMenInvited = UserConstants.ROOM_CARD_INVITED_AGENT;				
					}
					
					// 第一次创建用户 给邀请人赠送房卡
					//userService.addPlayerCard(parentPlayerInfo.getUserId(), roomCardMenInvited);
					userService.invitedAddPlayerCard(prarentUser, parentPlayerInfo, roomCardMenInvited,userinfoJson.get("nickname").getAsString());
					// 推送邀请信息
					retParentMes( access_token, userinfoJson.get("nickname").getAsString(),prarentUser,roomCardMenInvited);
					// 写入上 上级邀请ID
					if(upParentId!=0&&upParentId!=null){
						User upParentUser = userService.getById(upParentId);
						if(upParentUser!=null){
							upParentUser.setUpParentNub(upParentUser.getUpParentNub()==null?0:upParentUser.getUpParentNub()+1);
							userService.updateByPrimaryKeySelective(upParentUser);
						}
					}
				}
			}
			
			User newUser =new User();
			newUser.setOpenid(userinfoJson.get("openid").getAsString());
			newUser.setOutUserName(userinfoJson.get("nickname").getAsString());
			newUser.setHeadimgurl(userinfoJson.get("headimgurl").getAsString());
			newUser.setUnionid(userinfoJson.get("unionid").getAsString());
			newUser.setGameUserId(playerInfo==null?null:playerInfo.getGameId());  // 绑定玩家ID
			newUser.setAgentId(newUser.getGameUserId());
			newUser.setUserName(userinfoJson.get("nickname").getAsString());
			newUser.setPhone("");
			// 微信端默认代理商  推广大使 
			newUser.setUserType(UserConstants.USER_TYPE_WECHAT);
			newUser.setUserLevel(UserConstants.USER_LEVEL_TGDS);
			newUser.setEmail("");
			newUser.setPassword(Md5Util.encode("123456"));
			newUser.setRemark("公众号授权登录");
			newUser.setParentId(parentId);
			newUser.setParentNub(0);
			newUser.setAmount(0.0);
			newUser.setUpParentId(upParentId);
			newUser.setUpParentNub(0);
			newUser.setTotalCard(totalCard);
			newUser.setScore(0);
			newUser.setCreateTime(new Date());
			newUser.setStatus("0");
			newUser.setTiceng(0.0);
			newUser.setOutUserName(userinfoJson.get("nickname").getAsString());
			userService.insertSelective(newUser);
			User cuser=userService.getUserByUnionid(newUser.getUnionid());
			request.getSession().setAttribute("userSession", cuser);
			System.out.println("推送给消息");
		}
		return back;
	}
	
	
	
	
	
	
	public void retParentMes(String access_token,String nickName,User prarentUser,Integer roomCardMenInvited){
		//设置所属行业
		/*String setIndustry = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token="+access_token;
		String apijson ="{\"industry_id1\":\"1\", \"industry_id2\":\"2\"}";
		JsonObject setIndustryJson = WeixinUtil.HttpRequest(setIndustry, "POST", apijson);*/
		//if()
		
		// 获取设置的行业信息
		/*String  getIndustry="https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token="+access_token;
		JsonObject getIndustryJson = WeixinUtil.HttpRequest( getIndustry , "POST", null);*/
		
		//System.out.println("getIndustryJson:"+getIndustryJson); 
		
		// 获得模板ID
		/*String addTemplate = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token="+access_token;
		String template= "{\"template_id_short\":\"TM00007\"}" ;
		JsonObject templateJson = WeixinUtil.HttpRequest( addTemplate , "POST", template);
		
		System.out.println("templateJson："+templateJson);*/
		//String template_id = "x0tLilQNQCBYlA-NGkpklPp7CWp_0XoEB34-qj_ID7g";// 
		String titile = " 亲爱的  "+prarentUser.getOutUserName()+" ,【"+nickName+"】 已通过扫描您的分享二维码成为您的粉丝新用户，您已获赠"+roomCardMenInvited+"张房卡。";
		
		String invate= prarentUser.getOutUserName();
		String inscribe =" 分享越多，收获越多！"+wechatAccounts+"感谢您的支持！";
		
		if(!StringUtil.equals(prarentUser.getUserLevel(), UserConstants.USER_LEVEL_TGDS)||StringUtil.equals(prarentUser.getUserType(), UserConstants.USER_TYPE_MANAGE)){
			 titile = " 尊敬的  "+prarentUser.getOutUserName()+" ,【"+nickName+"】 已通过扫描您的分享二维码成为您的粉丝新用户，您已获赠"+roomCardMenInvited+"张房卡，并可享受粉丝用户的消费分红。";
			 inscribe ="分享的越多，收益越多！点点手指轻松赚外快！感谢您的支持!";
		}
		
		String template_id = "dxPeSDcvCJM0A0Lwv4ldFEe_9hEYrRrp4BsWexrW0zQ";//templateJson.get("template_id").getAsString();
		//发送模板消息
		String send = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
		
		String sendJosn = "{\"touser\":\""+prarentUser.getOpenid()+"\", \"template_id\":\""+template_id+"\" " +
				//"url":"http://weixin.qq.com/download",  
				//"miniprogram":{
				//"appid":"xiaochengxuappid12345",
				//"pagepath":"index?foo=bar"
				//		"},  "+        
		           ",\"data\":{ "+
						"\"first\": {  "+
							"\"value\":\" "+titile+" \", "+
							"\"color\":\"#173177\" "+
		                  " }, "+
		                   "\"keyword1\":{ "+
		                       "\"value\":\""+nickName+" \", "+
		                       "\"color\":\"#173177\" "+
		                 "  }, "+
		                   "\"keyword2\":{ "+
		                       "\"value\":\" "+invate +" \", "+
		                       "\"color\":\"#173177\" "+
		                 "  }, "+
		                   "\"keyword3\":{ "+
		                       "\"value\":\""+DateUtil.getCurrentLongTime()+" \", "+
		                       "\"color\":\"#173177\" "+
		                 "  }, "+
		                 "  \"remark\":{ "+
		                 "       \"value\":\" "+inscribe+" \", "+
		                 "       \"color\":\"#173177\" "+
		                 "   } } }"; 
		
		JsonObject sendJson = WeixinUtil.HttpRequest( send , "POST", sendJosn);
		logger.info("推送消息返回:" + sendJson);
	}
	
	
	public void retMessage(Message message){
		
		String access_token = WeixinUtil.getAccessToken(WechatPayProperties.getAppId(),WechatPayProperties.getAppSecret()).getToken();
		
		String send = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
		String backContext ="亲爱的用户，邀请新用户玩游戏，对方扫码下载安装后即成为你的粉丝用户，对方可获赠"+UserConstants.ROOM_CARD_INVITED+"张房卡，您也可获赠"+UserConstants.ROOM_CARD_INVITED+"张房卡，"+
				"且对方买房卡的消费您都有30%的分红哦，分享越多收益越多！建群玩游戏，轻轻松松外快过万！";
		
		// 拼装回复消息
		String  sendJosn="<xml><ToUserName><![CDATA["+message.getFromUserName()+"]]></ToUserName>"
				+"<FromUserName><![CDATA["+message.getToUserName()+"]]></FromUserName>"
				+"<CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType>"
				+"<Content><![CDATA["+backContext+"]]></Content></xml>";
		JsonObject sendJson = WeixinUtil.HttpRequest( send , "POST", sendJosn);
		System.out.println("sendJson:"+sendJson);
	}
	
	
	public String kefu(HttpServletRequest request,Message message) throws Exception{
		// 将回复消息序列化为xml形式
		createUserInfo( request, message);
		String  back="<xml><ToUserName><![CDATA["+message.getFromUserName()+"]]></ToUserName>"
				+"<FromUserName><![CDATA["+message.getToUserName()+"]]></FromUserName>"
				+"<CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType>"
				+"<Content><![CDATA[ 客服微信：xianle6688 \n 客服QQ：2806423585 ]]></Content></xml>";
		return back;
	}
	
	/**
	 * 推送二维码信息
	 * @param request
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public String showQrCode(HttpServletRequest request,Message message) throws Exception{
		// 将回复消息序列化为xml形式
		System.out.println("用户openID:"+message.getFromUserName());
		User user =userService.getUserByOpenid(message.getFromUserName());
		if(user==null){
			createUserInfo( request, message);
			/*String  back="<xml><ToUserName><![CDATA["+message.getFromUserName()+"]]></ToUserName>"
					+"<FromUserName><![CDATA["+message.getToUserName()+"]]></FromUserName>"
					+"<CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType>"
					+"<Content><![CDATA[ 正在创建，请稍后~~ ]]></Content></xml>";
			return back;*/
			user =userService.getUserByOpenid(message.getFromUserName());
		}
		if(user.getGameUserId()==null){
			if(user.getUnionid()!=null){
				PlayerInfo parentPlayerInfo = userService.getPlayerInfo(null, user.getUnionid());
				if(parentPlayerInfo==null){
					String  back="<xml><ToUserName><![CDATA["+message.getFromUserName()+"]]></ToUserName>"
							+"<FromUserName><![CDATA["+message.getToUserName()+"]]></FromUserName>"
							+"<CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType>"
							+"<Content><![CDATA[尊敬的用户你好，请先下载app,才能生成游戏邀请码，谢谢支持 ~~ ]]></Content></xml>";
					return back;
				}else{
					user.setGameUserId(parentPlayerInfo.getGameId());
					userService.updateByPrimaryKeySelective(user);
				}
			}
		}
		
		
		
		
		String imgjson = getImages(user);//getImages(user);
		JsonObject json = JsonUtil.fromJson(imgjson, JsonObject.class);
		String mediaId = json.get("media_id").getAsString();
		// json.get("url").getAsString();//.replace("\\", "");
		String imgret = "<xml><ToUserName><![CDATA["+message.getFromUserName()+"]]></ToUserName>"+
				"<FromUserName><![CDATA["+message.getToUserName()+"]]></FromUserName>"+
				" <CreateTime>12345678</CreateTime>"+
				" <MsgType><![CDATA[image]]></MsgType>"+
				"<Image>"+
				"<MediaId><![CDATA["+mediaId+"]]></MediaId>"+
				"</Image>"+
				" </xml>";
		return imgret;
		
	}
	
	
	
	
	
	
	/**
	 * 创建临时带参数二维码
	 * @param accessToken
	 * @expireSeconds 该二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
	 * @param sceneId  场景Id
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public String getImages(User user) {
		ImgUtil img= new ImgUtil();
		String access_token = WeixinUtil.getAccessToken(WechatPayProperties.getAppId(),WechatPayProperties.getAppSecret()).getToken();
		String showUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";  
        showUrl = showUrl.replace("TICKET", WeixinUtil.createTemporaryORCode(access_token, "2592000", (user.getAgentId()==null?user.getGameUserId():user.getAgentId()).toString()));
		String path = img.createImg(showUrl,1);
		String returnMsg = img.postFile(path,access_token);
		System.out.println(" 生成成功   path:"+path +"- returnMsg:"+returnMsg);
		return returnMsg;
	}
	
	/**
	 * 创建临时带参数二维码链接
	 * @param accessToken
	 * @expireSeconds 该二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
	 * @param sceneId  场景Id
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public String getImagesPath(User user) {
		ImgUtil img= new ImgUtil();
		String access_token = WeixinUtil.getAccessToken(WechatPayProperties.getAppId(),WechatPayProperties.getAppSecret()).getToken();
		// 邀请链接
		String codePath = WechatPayProperties.getInviteUrl() +"?gameId="+user.getAgentId();
		//图片路径
		String file = img.createQrCode(codePath);
		// 合成图片
		String path = img.createImg(file,2);
		// 上传服务器
		String returnMsg = img.postFile(path,access_token);
		return returnMsg;
	}
	
	
	
	/**
	 * 根据token计算signature验证是否为微信服务端发送的消息
	 * @param request
	 * @return
	 */
	private static boolean checkWeixinReques(HttpServletRequest request){
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		if (signature != null && timestamp != null && nonce != null ) {
			String[] strSet = new String[] { WeixinUtil.TOKEN, timestamp, nonce };
			java.util.Arrays.sort(strSet);
			String key = "";
			for (String string : strSet) {
				key = key + string;
			}
			String pwd = WeixinUtil.sha1(key);
			return pwd.equals(signature);
		}else {
			return false;
		}
	}
	
	



	

}
